import React, { Component, Fragment } from 'react';
import { connect } from 'dva';
import {Button, Modal, Row,Col,Steps,Card,Badge,Collapse,Tabs, BackTop,Layout,Tag } from 'antd';
import DescriptionList from 'components/DescriptionList';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from './Testreport.less'
import { Editor } from 'react-draft-wysiwyg';
import { EditorState, convertToRaw, ContentState } from 'draft-js'
import draftToHtml from 'draftjs-to-html';
import htmlToDraft from 'html-to-draftjs';
import BasicEditFrom from './BasicEditFrom';
import '../../../node_modules/react-draft-wysiwyg/dist/react-draft-wysiwyg.css';
const { Description } = DescriptionList;
const ButtonGroup = Button.Group


@connect(({ testreport, project, user, loading }) => ({
  testreport,
  ActiveReport: testreport.activeReport,
  basicVisible: testreport.basicvisible,
  EditVisible1: testreport.editvisible1,
  EditVisible2: testreport.editvisible2,
  EditVisible3: testreport.editvisible3,
  pc:testreport.pc,
  web:testreport.web,
  mobile:testreport.mobile,
  CurrentUserProjectList: project.currentUserOwnedProjectList,
  currentUser: user.currentUser,
  loading: loading.models.testreport
}))

export default class TestReport extends Component{

  
  action =() =>{
    return(
      <ButtonGroup>
        <Button>编辑</Button>
        <Button>导出</Button>
      </ButtonGroup>
    );
  }

  state = {
    editorState1: EditorState.createEmpty(),
    editorState2: EditorState.createEmpty(),
    editorState3: EditorState.createEmpty(),
    textedit1:'编辑',
    textedit2:'编辑',
    textedit3:'编辑',
    editText:true
  }

  componentWillMount(){ 
    let reportId = this.props.match.params.reportId
    this.props.dispatch({
      type:'testreport/queryActiveReport',
      payload: reportId
    })
    
    this.props.dispatch({
      type:'project/queryCurrentUserOwnedProjects'
    })

    this.props.dispatch({
      type:'user/fetchCurrent'
    })

    this.props.dispatch({
      type:'testreport/getDataArray'
    })
  }

  initText = () =>{
    const reportData = this.props.ActiveReport
    const contentBlock1 = htmlToDraft(reportData.modify)
    const contentBlock2 = htmlToDraft(reportData.summary)
    const contentBlock3 = htmlToDraft(reportData.risk)
    if (contentBlock1) {
      const contentState = ContentState.createFromBlockArray(contentBlock1.contentBlocks);
      const editorState = EditorState.createWithContent(contentState);
      this.setState({ editorState1: editorState })
    }
    if (contentBlock2) {
      const contentState = ContentState.createFromBlockArray(contentBlock2.contentBlocks);
      const editorState = EditorState.createWithContent(contentState);
      this.setState({ editorState2: editorState })
    }
    if (contentBlock3) {
      const contentState = ContentState.createFromBlockArray(contentBlock3.contentBlocks);
      const editorState = EditorState.createWithContent(contentState);
      this.setState({ editorState3: editorState })
    }
  }

  
  loading = (data) =>{
    if(!data==''){
      return data.testdata
    }else{
      let load = {
        suggest:0,
        newbug:0,
        deadly:0,
        serious:0,
        commom:0,
        tips:0,
        verify:0,
        verifyfail:0,
        totalbug:0,
        block:0
      }
      return load
    }
  }

  basicEdit = ()=>{
    this.props.dispatch({
      type:'testreport/setFormModalVisible',
      payload: true
    })
  }

  updateTestData = () =>{
    let reportData = this.props.ActiveReport
    this.props.dispatch({
      type:'testreport/updetaTestData',
      payload:{
        id:parseInt(reportData.key),
        pname:reportData.name,
        version:reportData.version
      }
    })
  }

  releaseReport = ()=>{
    let reportData = this.props.ActiveReport

    let updetaTestState = () =>{
      this.props.dispatch({
        type:'testreport/releaseReport',
        payload: {id:parseInt(reportData.key)}
      })
    }
    Modal.confirm({
      title: '请确认测试报告内容后发布',
      content: '发布后测试报告内容无法更改',
      onOk() {updetaTestState()},
      onCancel() {}
    });  
  }



  textEdit1 = () =>{
    if(this.state.textedit1=='编辑'){
      this.props.dispatch({
        type:'testreport/setEditModalvisible',
        payload:{editvisible1:true}
      })
      this.setState({
        textedit1:'保存'
      })
    }else{
      this.props.dispatch({
        type:'testreport/setEditModalvisible',
        payload: {editvisible1:false}
      })
      this.setState({
        textedit1:'编辑'
      })
      
      this.props.dispatch({
        type:'testreport/editTextReport',
        payload:{
          id:parseInt(this.props.match.params.reportId),
          type:1,
          text:draftToHtml(convertToRaw(this.state.editorState1.getCurrentContent()))
        }
      })
    }   
  }

  textEdit2 = () =>{
    if(this.state.textedit2=='编辑'){
      this.props.dispatch({
        type:'testreport/setEditModalvisible',
        payload:{editvisible2:true}
      })
      this.setState({
        textedit2:'保存'
      })
    }else{
      this.props.dispatch({
        type:'testreport/setEditModalvisible',
        payload: {editvisible2:false}
      })
      this.setState({
        textedit2:'编辑'
      })

      this.props.dispatch({
        type:'testreport/editTextReport',
        payload:{
          id:parseInt(this.props.match.params.reportId),
          type:2,
          text:draftToHtml(convertToRaw(this.state.editorState2.getCurrentContent()))
        }
      })
    }   
  }

  textEdit3 = () =>{
    if(this.state.textedit3=='编辑'){
      this.props.dispatch({
        type:'testreport/setEditModalvisible',
        payload: {editvisible3:true}
      })
      this.setState({
        textedit3:'保存'
      })
    }else{
      this.props.dispatch({
        type:'testreport/setEditModalvisible',
        payload: {editvisible3:false}
      })
      this.setState({
        textedit3:'编辑'
      })

      this.props.dispatch({
        type:'testreport/editTextReport',
        payload:{
          id:parseInt(this.props.match.params.reportId),
          type:3,
          text:draftToHtml(convertToRaw(this.state.editorState3.getCurrentContent()))
        }
      })
    }   
  }

  onEditorStateChange1 = (editorState) => {
    this.setState({
      editorState1:editorState,
    });
  };
  onEditorStateChange2 = (editorState) => {
    this.setState({
      editorState2:editorState,
    });
  };
  onEditorStateChange3 = (editorState) => {
    this.setState({
      editorState3:editorState,
    });
  };

  testResult =(data) =>{
    switch (data){
      case 0 :
        return ('不通过')
      
      case 1:
        return('通过') 
      
      case 2: 
        return ('未开始')  
      
      case 3:
        return('测试中')  
    }
  }

  Percentage = (number,total)=>{
    let a =(number/total)*100
    if(total==0){
      a =0
    }
    let b = a.toFixed(2)
    return b
  }
  
  netWorkTag =(tags)=>{
    tags.map((tag) => {
      const tagElem = (
        <Tag key={tag} >
          {tag}
        </Tag>
      );
      return tagElem;
    })
  }

  editJurisdiction = (value) =>{
    // console.log('list..',this.props.CurrentUserProjectList)
    const reportData = this.props.ActiveReport
    let isUserInProject = this.props.CurrentUserProjectList.some(cp => {
      return cp.id == reportData.projectId;
    })
    let currentUser = this.props.currentUser
    if(reportData.state==1){
      if(isUserInProject&&currentUser.roleId===3){
        return value
      }else{
        return ''
      }
    }else if(reportData.state==0){
      return ''
    }
  }

  releaseJurisdiction = () =>{
    const reportData = this.props.ActiveReport
    let isUserInProject = this.props.CurrentUserProjectList.some(cp => {
      return cp.id == reportData.projectId;
    })
    let currentUser = this.props.currentUser
    if(reportData.state==1){
      if(isUserInProject&&currentUser.roleId===3){
        return  <Button type = 'primary' size = {"large"} onClick={this.releaseReport.bind(this)}>发布</Button>
      }else{
        return ''
      }
    }else if(reportData.state==0){
      return ''
    }
  }

  getEquipment =(pc,web,mobile) =>{
    
    let equipment ={
      pc:pc? pc:[],
      web:web? web:[],
      移动端:mobile? mobile:[]
    }

    return equipment
  }
  
  render(){
    const reportData = this.props.ActiveReport
    const testData = this.loading(reportData)
    if(reportData&&this.state.editText){
      this.initText()
      this.setState({editText:false})
    }
    const { editorState1,editorState2,editorState3 } = this.state;
    let textarea1;
    let textarea2;
    let textarea3;
    if (this.props.EditVisible1==true){
      textarea1 = (
        <Editor
          editorState={editorState1}
          localization={{ locale: 'zh' }}
          wrapperClassName= {styles.wrapper}
          editorClassName={styles.editor}
          onEditorStateChange={this.onEditorStateChange1}
        />
      )
    }else{
      textarea1 = (
        <div dangerouslySetInnerHTML={{__html: reportData.modify}}></div>
      )
    }
    
    if (this.props.EditVisible2==true){
      textarea2 = (
        <Editor
          editorState={editorState2}
          localization={{ locale: 'zh' }}
          wrapperClassName= {styles.wrapper}
          editorClassName={styles.editor}
          onEditorStateChange={this.onEditorStateChange2}
        />
      )
    }else{
      textarea2 = (
        <div dangerouslySetInnerHTML={{__html: reportData.summary}}></div>
      )
    }
    
    if (this.props.EditVisible3==true){
      textarea3 = (
        <Editor
          editorState={editorState3}
          localization={{ locale: 'zh' }}
          wrapperClassName= {styles.wrapper}
          editorClassName={styles.editor}
          onEditorStateChange={this.onEditorStateChange3}
        />
      )
    }else{
      textarea3 = (
        <div dangerouslySetInnerHTML={{__html: reportData.risk}}></div>
      )
    }
    
    return(
      <PageHeaderLayout
        title = {`${reportData.name} ${reportData.version}测试报告`}
        // logo={<img alt="" src="../src/assets/mBlock1.png" />}
        extraContent={this.releaseJurisdiction()}
      > 
        <Card title = '基本信息' className = {styles.card}  extra={<a onClick={this.basicEdit}>{this.editJurisdiction('编辑')}</a>}>
          <DescriptionList className={styles.headerList} size="large" col="2">
            <Description term="测试任务名称">{`${reportData.name} ${reportData.version}`}</Description>
            <Description term="测试结论">{this.testResult(reportData.status)}</Description>
            <Description term="测试周期">{`${reportData.startTime} 至 ${reportData.endTime}`}</Description>
            <Description term="执行工作量">{`${reportData.workload}人/日`}</Description>
            <Description term="测试执行人员">{reportData.tester}</Description>
            <Description term="测试版本">{reportData.version}</Description>
          </DescriptionList>
          <Row>
            <Col span = {2}>
            <p>网络</p>
            </Col >
            <Col span = {22}>
              {reportData.network? reportData.network.map((tag) => {
                const tagElem = (
                  <Tag color="#2db7f5" key={tag} >
                    {tag}
                  </Tag>
                );
                return tagElem;
              }):''}
            </Col>
          </Row>
          <Row>
            <Col span = {2}>
              <p>测试范围</p>
            </Col>
            <Col span = {22}>
              {reportData.testRange? reportData.testRange.map((tag) =>{
                const tagElem = (
                  <Tag color="#2db7f5" key={tag} >
                    {tag}
                  </Tag>
                );
                return tagElem;
              }):""}
            </Col>
          </Row>
          <Row>
            <Col span = {2}>
              <p>机型</p>
            </Col>
            <Col span = {22}>
              {reportData.testRange? reportData.equipment.map((tag) =>{
                const tagElem = (
                  <Tag color="#2db7f5" key={tag} >
                    {tag}
                  </Tag>
                );
                return tagElem;
              }):""}
            </Col>
          </Row>
        </Card>
        
        <Card title = '测试总结与分析' className = {styles.card}  extra={<a onClick={this.updateTestData}>{this.editJurisdiction('更新')}</a>}>
          <Row gutter={24}>
            <Col xl={{ span: 4}}>提交产品建议总数</Col>
            <Col span = {20}>
              <Row>
                <Col xl={{ span: 4}}>新发现bug总数</Col>
                <Col xl={{ span: 4}}>致命</Col>
                <Col xl={{ span: 4}}>严重</Col>
                <Col xl={{ span: 4}}>一般</Col>
                <Col xl={{ span: 4}}>提示</Col>  
              </Row>
            </Col>
          </Row>
          <Row gutter={24}>
            <Col xl={{ span: 4 }}>{testData.suggest}</Col>
            <Col xl={{ span: 20}}>
              <Row>
                <Col xl={{ span: 4}}>{testData.newbug}</Col>
                <Col xl={{ span: 4}}>{testData.deadly}</Col>
                <Col xl={{ span: 4}}>{testData.serious}</Col>
                <Col xl={{ span: 4}}>{testData.commom}</Col>
                <Col xl={{ span: 4}}>{testData.tips}</Col>
              </Row>
              <Row>
                <Col xl={{ span: 4}}>Bug占比情况</Col>
                <Col xl={{ span: 4}}>{`${this.Percentage(testData.deadly,testData.newbug)}%`}</Col>
                <Col xl={{ span: 4}}>{`${this.Percentage(testData.serious,testData.newbug)}%`}</Col>
                <Col xl={{ span: 4}}>{`${this.Percentage(testData.commom,testData.newbug)}%`}</Col>
                <Col xl={{ span: 4}}>{`${this.Percentage(testData.tips,testData.newbug)}%`}</Col>
              </Row>
            </Col>
          </Row>
          <Row gutter={24}>
            <Col xl={{ span: 4}}>回归Bug数</Col>
            <Col span = {20}>
              <Row>
                <Col xl={{ span: 4}}>回归不通过bug数</Col>
                <Col xl={{ span: 4}}>回归通过率</Col>
                <Col xl={{ span: 4}}>累计有效bug数</Col>
                <Col xl={{ span: 4}}>累计挂起bug数</Col>
                <Col xl={{ span: 4}}>挂起率</Col>  
              </Row>
            </Col>
          </Row>
          <Row gutter={24}>
            <Col xl={{ span: 4}}>{testData.verify? testData.verify:0}</Col>
            <Col span = {20}>
              <Row>
                <Col xl={{ span: 4}}>{testData.verifyfail?testData.verifyfail:0}</Col>
                <Col xl={{ span: 4}}>{`${this.Percentage((testData.verify-testData.verifyfail),testData.verify)}%`}</Col>
                <Col xl={{ span: 4}}>{testData.totalbug}</Col>
                <Col xl={{ span: 4}}>{testData.block}</Col>
                <Col xl={{ span: 4}}>{`${this.Percentage(testData.block,testData.totalbug)}%`}</Col>  
              </Row>
            </Col>
          </Row>
        </Card>
        <Card title = '新增功能/修改点' className = {styles.card} extra={<a onClick={this.textEdit1}>{this.editJurisdiction(this.state.textedit1)}</a>}>
        {/* <div dangerouslySetInnerHTML={{__html: reportData.modify}}></div> */}
        {textarea1}
        </Card>
        <Card title = '测试小结' className = {styles.card} extra={<a onClick={this.textEdit2}>{this.editJurisdiction(this.state.textedit2)}</a>}>
        {/* <div dangerouslySetInnerHTML={{__html: reportData.modify}}></div> */}
        {textarea2} 
        </Card>
        <Card title = '风险点及遗留问题' className = {styles.card} extra={<a onClick={this.textEdit3}>{this.editJurisdiction(this.state.textedit3)}</a>}>
        {textarea3}
        </Card>
        
        <BasicEditFrom
          visible = {this.props.basicVisible}
          data = {reportData}
          equipment = {this.getEquipment(this.props.pc,this.props.web,this.props.mobile)}
        />
        
      </PageHeaderLayout>
      
    );
  }    
}

